//
//  GKShopItemController.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2020/9/9.
//  Copyright © 2020 wangws1990. All rights reserved.
//

import UIKit

class GKShopItemController: BaseTableViewController {
    convenience init(rankId :String) {
        self.init()
        self.rankId = rankId
    }
    public var rankId :String? = nil
    lazy var listData : [GKBook] = {
        return []
    }()
    override func vtm_prepareForReuse() {
        self.listData.removeAll()
        self.tableView.reloadData()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupRefresh(scrollView: self.tableView, options: .defaults);
    }
    override func refreshData(page: Int) {
        guard let rankId = self.rankId else { return }
        ApiMoya.request(target: .homeHot(rankId)) { json in
            if page == RefreshPageStart{
                self.listData.removeAll()
            }
            guard let info =  GKHomeInfo.deserialize(from: json["ranking"].rawString())else {
                return self.endRefreshFailure()
            }
            self.listData.append(contentsOf: info.books)
            self.tableView.reloadData()
            self.endRefresh(more: false)
        } failure: { error in
            self.endRefreshFailure()
        }
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listData.count
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell  = GKClassifyTailCell.cellForTableView(tableView: tableView, indexPath: indexPath)
        cell.model = self.listData[indexPath.row]
        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated:true)
        let model = self.listData[indexPath.row]
        GKJump.jumpToDetail(bookId: model.bookId)
    }
}
